package com.iwjw.ibatis.plugins.explain;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: huangweiwei
 * @email: ihuangweiwei@163.com
 * @created:2016/11/3
 */
@AllArgsConstructor
public enum ExplainSqlType {
    /**
     * system > const > eq_ref > ref > fulltext > ref_or_null  >
     * index_merge > unique_subquery > index_subquery > range >
     * index > ALL（优-->差）
     * 一般来说，得保证查询至少达到range级别，最好能达到ref，否则就可能会出现性能问题;
     */
    SYSTEM(0),
    CONST(1),
    EQ_REF(2),
    REF(3),
    FULLTEXT(4),
    REF_OR_NULL(5),
    INDEX_MERGE(6),
    UNIQUE_SUBQUERY(7),
    RANGE(8),
    INDEX(9),
    ALL(10);

    /**
     * 谁最LOW
     */
    @Getter
    private int lower;


    /**
     * 比较不错的SQL
     * @param explainSqlType
     * @return
     */
    public static boolean isGood(ExplainSqlType explainSqlType){
        return explainSqlType.getLower()<=ExplainSqlType.REF.getLower();
    }

    /**
     * 勉强及格
     * @param explainSqlType
     * @return
     */
    public static boolean isSimple(ExplainSqlType explainSqlType){
        return explainSqlType.getLower()<=ExplainSqlType.RANGE.getLower();
    }

    /**
     * 是否突破指定的底线
     *
     * @param explainSqlType
     * @param baseLine
     * @return
     */
    public static boolean isBreakBaseLine(ExplainSqlType explainSqlType,ExplainSqlType baseLine){
        return explainSqlType.getLower()>baseLine.getLower();
    }

    /**
     * 获取对应的SQL执行Type等级
     * @param name
     * @return
     */
    public static ExplainSqlType get(String name){
        if(StringUtils.isEmpty(name)){
            return ExplainSqlType.ALL;
        }
        for(ExplainSqlType explainSqlType:values()){
            if(explainSqlType.name().toLowerCase().equals(name.toLowerCase())){
                return explainSqlType;
            }
        }
        return ExplainSqlType.ALL;
    }

}
